//
//  SEHospitalizeLocationCell.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/5/27.
//

import UIKit

protocol SEHospitalizeLocationCellDelegate: NSObjectProtocol {
    func hospitalizeLocationCell(_ cell: SEHospitalizeLocationCell, didSelectRowAt indexPath: IndexPath)
}

class SEHospitalizeLocationCell: UITableViewCell {
    
    weak var delegate: SEHospitalizeLocationCellDelegate?
    
    private var viewModel: SEHospitalizeViewModel?

    func update(with viewModel: SEHospitalizeViewModel) {
        self.viewModel = viewModel
        containerViewViewHeightConstraint.constant = 75 * CGFloat(viewModel.numberOfLocationRows)
        tableView.reloadData()
    }
    
    @IBOutlet private var containerViewViewHeightConstraint: NSLayoutConstraint!
    
    @IBOutlet private weak var containerView: UIView! {
        didSet {
            containerView.backgroundColor = Asset.white.color
            containerView.setLayerCorners(rect: containerView.bounds, radius: 14)
            containerView.setShadow()
        }
    }
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = Asset.white.color
            tableView.clipsToBounds = true
            tableView.setLayerCorners(rect: tableView.bounds, radius: 14)
            tableView.isScrollEnabled = false
            tableView.tableFooterView = UIView()
            tableView.estimatedRowHeight = 75
            tableView.rowHeight = UITableView.automaticDimension
            tableView.delegate = self
            tableView.dataSource = self
            
            tableView.register(SEHospitalizeLocationChildCell.nibForCell(),
                               forCellReuseIdentifier: SEHospitalizeLocationChildCell.reuseIdentifier())
        }
    }
}

extension SEHospitalizeLocationCell: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfLocationRows ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalizeLocationChildCell.reuseIdentifier(),
                                                 for: indexPath) as! SEHospitalizeLocationChildCell
        if let vm = viewModel {
            let hospitalItem = vm.hospitalListViewModel.listItem(indexPath: indexPath)
            cell.update(with: hospitalItem, lineHidden: indexPath.row == vm.numberOfLocationRows - 1)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        delegate?.hospitalizeLocationCell(self, didSelectRowAt: indexPath)
    }
}
